//
//  TSLoginViewController.swift
//  TopStock
//
//  Created by dyd on 2017/8/6.
//  Copyright © 2017年 dyd. All rights reserved.
//

import UIKit


class TSLoginViewController: UIViewController {

    @IBOutlet weak var phoneNumTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    let request = TSRequestData()
    var isFromSetting:Bool = false
    override func viewDidLoad() {
        super.viewDidLoad()
        
//        let deviceModel = UIDevice.current.model
        self.title = "账号登陆"
        setInitPhoneNumber()
        NotificationCenter.default.addObserver(self,selector: #selector(WXLoginSuccess(notification:)),name:   NSNotification.Name(rawValue: "WXLoginSuccessNotification"),object: nil)
        self.setBackItem()
    }
    
    func setInitPhoneNumber()
    {
        let phoneNum = UserDefaults.standard.object(forKey: KPhoneNumberKey) as? String
        if phoneNum != nil{
            phoneNumTextField.text = phoneNum
        }
    }
    
    func setBackItem(){
        let item = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(dismissView))
        self.navigationItem.leftBarButtonItem = item
        self.navigationItem.leftBarButtonItem?.tintColor = BarButtonItemTintColor
    }
    
    func dismissView(){
        if isFromSetting{
            NotificationCenter.default.post(name:NSNotification.Name(rawValue: "webViewRefresh"), object: nil, userInfo: nil)
            self.dismiss(animated: true, completion: nil)
        }else{
            self.dismiss(animated: true, completion: nil)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setNavBarAppearance()
    }
    
    func setNavBarAppearance(){
        let navBar=UINavigationBar.appearance()
        navBar.titleTextAttributes = NavBarTitleTextAttributes
        navBar.tintColor = UIColor.black
        navBar.barTintColor = BarTintColor
        UIApplication.shared.statusBarStyle = .lightContent
    }
    
//    func setNavBarAppearance(){
//        UIApplication.shared.statusBarStyle = .`default`
//    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        passwordTextField.text = ""
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func thirdPartyLogins(_ sender: Any) {
       alertViewController()
    }

    //手机号码登陆
    @IBAction func LoginBtnAction(_ sender: Any) {
        hideKeyboard(sender)
        let phoneNum = phoneNumTextField.text
        let password = passwordTextField.text
        let isSure = telPoneNumAndPasswordDetection(phoneNum: phoneNum, password: password)
        if isSure{
            let requestDic = request.login(phoneNumber: phoneNum!, password: password!)
            if requestDic != nil{
                let success:Bool = requestDic!["success"]! as! Bool
                if success{
                    let accessTokenDic = requestDic?["data"] as! NSDictionary
                    let accessToken = accessTokenDic["access_token"] as? String
                    if (accessToken != nil){
                        UserDefaults.standard.set(accessToken, forKey: KAccessToken)
                    }
                    UserDefaults.standard.set(phoneNum, forKey: KPhoneNumberKey)
                    showRootView()
                }else{
                    let errorDic = requestDic!["error"]! as! NSDictionary
                    let errorStr = errorDic["errorInfo"] as! String
                    showAlertView(title: nil, message: errorStr)
                }
            }else{
                showAlertView(title: nil, message: "请检查网络")
            }
        }
    }
    
    //输入号码和密码前需要检查
    func telPoneNumAndPasswordDetection(phoneNum:String?,password:String?) ->Bool{
        let isTelNumbe = TSMobileNumberManger.isTelPhoneNumber(telNumber: phoneNum!)
        if (!isTelNumbe){
            showAlertView(title: nil, message: "请输入正确手机号码")
            return false
        }
        if (password?.isEmpty)!{
            showAlertView(title: nil, message: "密码不能为空")
            return false
        }else{
            return true
        }
    }
    
    //异常error显示
    
    func showAlertView(title:String?,message:String?)
    {
        let alertController = UIAlertController(title: title,
                                                message: message, preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default, handler: {
            action in
        })
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    func showRootView()
    {
        NotificationCenter.default.post(name:NSNotification.Name(rawValue: "webViewRefresh"), object: nil, userInfo: nil)
        self.dismiss(animated: true, completion: nil)
//        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
//        let rootViewController = storyBoard.instantiateViewController(withIdentifier: "RootViewController") as! TSRootViewController
//        let rootNav = UINavigationController.init(rootViewController: rootViewController)
//        self.present(rootNav, animated: true, completion: nil)
    }

    
    @IBAction func hideKeyboard(_ sender: Any)//隐藏键盘
    {
        phoneNumTextField.resignFirstResponder()
        passwordTextField.resignFirstResponder()
    }
    
    // MARK: - 微信授权登陆
    func weixinLogin()
    {
        let urlStr = "weixin://"
        if UIApplication.shared.canOpenURL(URL.init(string: urlStr)!) {
            let red = SendAuthReq.init()
            red.scope = "snsapi_message,snsapi_userinfo,snsapi_friend,snsapi_contact"
            red.state = "\(arc4random()%100)"
            let statsu = WXApi.send(red)
            print("statsu ==>:\(statsu)")
        }else{
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(URL.init(string: "http://weixin.qq.com/r/qUQVDfDEVK0rrbRu9xG7")!, options: [:], completionHandler: nil)
            } else {
                // Fallback on earlier versions
                UIApplication.shared.openURL(URL.init(string: "http://weixin.qq.com/r/qUQVDfDEVK0rrbRu9xG7")!)
            }
        }
    }
    
    func WXLoginSuccess(notification:Notification) {
        let WX_APPID = "wxb4ce4301a703b851"
        let WX_APPSecret = "6a84b426f1e641daa62f8b6da8bcbe65"
        let code = notification.object as! String
        let requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=\(WX_APPID)&secret=\(WX_APPSecret)&code=\(code)&grant_type=authorization_code"
        
        DispatchQueue.global().async {
            let requestURL: URL = URL.init(string: requestUrl)!
            let data = try? Data.init(contentsOf: requestURL, options: Data.ReadingOptions())
            DispatchQueue.main.async {
                let jsonResult = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
                if jsonResult != nil
                {
                    let openid = jsonResult!["openid"] as? String
                    UserDefaults.standard.set(openid, forKey: KOpenID)
//                    let access_token = jsonResult!["access_token"] as? String
                    let WeixinDic = self.request.wechatLogin()?["data"] as? NSDictionary
                    print("WeixinDic ==>:\(WeixinDic)")
                    let access_tokenForWeiXin = WeixinDic?["access_token"] as? String
                    if access_tokenForWeiXin != nil{
                        UserDefaults.standard.set(access_tokenForWeiXin, forKey: KAccessToken)
                        self.showRootView()
                    }else{
                        self.showRegisterView()
                    }
//                    if (access_token != nil)&&(openid != nil){
//                        self.getWeiXinUserInfo(openid: openid!, access_token: access_token!)
//                    }
                }
            }
        }
    }
    
    //微信授权成功以后，获取用户信息
    func getWeiXinUserInfo(openid:String,access_token:String) {
        let requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=\(access_token)&openid=\(openid)"
        DispatchQueue.global().async {
            let requestURL: URL = URL.init(string: requestUrl)!
            let data = try? Data.init(contentsOf: requestURL, options: Data.ReadingOptions())
            DispatchQueue.main.async {
                if data != nil{
                    let jsonResult = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
                    if jsonResult != nil{
                        print("jsonResult =>:\(String(describing: jsonResult))")
                    }
                }
            }
        }
    }
    
    func alertViewController(){
        let alert = UIAlertController.init(title: "微信登陆", message: nil, preferredStyle: .alert)
        alert.addAction(UIAlertAction.init(title: "确定", style: .`default`, handler: {
            (UIAlertAction) -> Void in
            self.weixinLogin()
        }))
        self.present(alert, animated: true, completion: nil)
    }
    
    func showRegisterView()
    {
        let storyBoard : UIStoryboard = UIStoryboard(name: "Login", bundle: nil)
        let registerViewController = storyBoard.instantiateViewController(withIdentifier: "registerViewController") as! TSRegisterViewController
        registerViewController.isPhoneRegister = false
        self.present(registerViewController, animated: true, completion: nil)
    }
    
    // MARK: - Navigation
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "foundPassword" {
            let destinationNavigationController = segue.destination as! UINavigationController
            let destinationController = destinationNavigationController.topViewController as! TSFoundPasswordViewController
            destinationController.title = "找回密码"
        }
    }

}
